from PyQt4 import QtGui, QtCore
from os import path as File

import Aneke

class FileManager( QtGui.QTabWidget ):
	"""
	This widget controls the open files and their
	tabs. It takes care of the File menu entry also.
	"""
	
	basedir = ""
	"""
	Usualy the files that a programmer works on are
	in the same base directory.
	"""
	
	def __init__( self, initial_file="", parent=None ):
		QtGui.QTabWidget.__init__( self, parent )
		self.parentWindow = parent
		self.currentTab = -1
		
		nextTabAction = QtGui.QAction( self )
		nextTabAction.setShortcut( QtGui.QKeySequence( "Ctrl+PgDown" ))
		self.addAction( nextTabAction )
		self.connect(nextTabAction,QtCore.SIGNAL("triggered()"), self.nextTab)
		
		previousTabAction = QtGui.QAction( self )
		previousTabAction.setShortcut(  "Ctrl+PgUp" )
		self.addAction( previousTabAction )
		self.connect(previousTabAction,QtCore.SIGNAL("triggered()"), self.previousTab)
		
		self.connect(self, QtCore.SIGNAL("currentChanged(int)"),self.handleTabChange)
		
		if initial_file and not File.exists( initial_file ):
			self.newFile( initial_file )
			return
		
		if initial_file and File.isfile(initial_file):
			self.basedir = File.dirname(initial_file)
			self.openFile(initial_file)
		elif initial_file and File.isdir(initial_file):
			self.basedir = initial_file
		
	def getEditor( self ):
		"""
		Get the Aneke.Editor instance from the
		current tab.
		"""
		return self.currentWidget()
	
	def nextTab( self ):
		"""
		Set focus to the next tab.
		"""
		max_index = self.count() - 1
		if self.currentTab == max_index:
			self.currentTab = 0
		else:
			self.currentTab = self.currentTab + 1
			
		self.setCurrentIndex( self.currentTab )
		
	def previousTab( self ):
		"""
		Set focus to the previous tab
		"""
		max_index = self.count() - 1
		if self.currentTab == 0:
			self.currentTab = max_index
		else:
			self.currentTab = self.currentTab - 1
		
		self.setCurrentIndex( self.currentTab )
		
	def handleTabChange( self, newTab ):
		"""
		The callable for the currentChanged(int) signal reised
		by QTabWidget. This method set focus to the editor widget
		and update the window title so it shows the current filename
		"""
		editor = self.widget( newTab )
		editor.setFocus()
		
		title = self.tabText( newTab )
		self.parentWindow.updateTitle( title )
		
	def createEditorTab(self, name):
		"""
		Creates a new tab with an embeded Aneke.Editor instance.	
		"""		
		editor = Aneke.Editor( name )
		title  = name.split('/')[-1]
		
		return self.addTab( editor, title )
		
	def setupFileMenu( self, fileMenu ):
		"""
		Set the actions for the File menu
		"""
		newFileAct = QtGui.QAction(self.tr("&New"), fileMenu)
		newFileAct.setShortcut(QtGui.QKeySequence( "Ctrl+N" ))
		self.connect(
			newFileAct,
			QtCore.SIGNAL("triggered()"), 
			self.parentWindow.fileManager.newFile
		)
		fileMenu.addAction( newFileAct )
		
		openFileAct = QtGui.QAction(self.tr("&Open"), fileMenu)
		openFileAct.setShortcut(QtGui.QKeySequence( "Ctrl+O" ))
		self.connect(
			openFileAct, 
			QtCore.SIGNAL("triggered()"), 
			self.parentWindow.fileManager.openFile
		)
		fileMenu.addAction( openFileAct )
		
		closeFileAct = QtGui.QAction(self.tr("&Close"),fileMenu)
		closeFileAct.setShortcut(QtGui.QKeySequence( "Ctrl+W" ))
		self.connect(
			closeFileAct,
			QtCore.SIGNAL("triggered()"),
			self.parentWindow.fileManager.closeFile
		)
		fileMenu.addAction( closeFileAct )
		
		saveFileAct = QtGui.QAction(self.tr("&Save"),fileMenu)
		saveFileAct.setShortcut(QtGui.QKeySequence( "Ctrl+S" ))
		self.connect(
			saveFileAct, 
			QtCore.SIGNAL("triggered()"), 
			self.parentWindow.fileManager.saveFile
		)
		fileMenu.addAction( saveFileAct )
		
		fileMenu.addSeparator()
		
		fileMenu.addAction(
			self.tr("&Close"), 
			QtGui.qApp, 
			QtCore.SLOT("quit()"),
			QtGui.QKeySequence( "Ctrl+Q" )
		)
		
	def newFile( self, filename="" ):
		tabTitle = "Untitled " + str( self.currentTab + 1 )
		self.currentTab = self.createEditorTab( tabTitle )
		self.setCurrentIndex( self.currentTab )
		
		if self.count() == 1:
			self.handleTabChange( self.currentTab )
			
	def openFile(self, filename=""):
		if not filename:
			filename = QtGui.QFileDialog.getOpenFileName(
				self, 
				self.tr("Open File"), 
				"", 
				"All Files (*)"
			)

		if filename:
			file = open(filename,'r')
			if file:
				filename = filename.split('/')[-1]
				self.currentTab = self.createEditorTab( filename )
				self.widget( self.currentTab ).setPlainText( file.read() )
			
		self.setCurrentIndex( self.currentTab )
		
	def closeFile( self ):
		editor 	= self.getEditor()
		if editor.filename:
			self.saveFile( editor.filename )
		self.removeTab( self.currentTab )
		if self.count() == 0:
			self.parentWindow.resetTitle()
		else:
			self.currentTab = self.currentIndex()
			self.setCurrentIndex( self.currentTab )

	def saveFile(self, filename=""):
		editor 		 = self.getEditor()
		
		if editor.filename:
			filename = editor.filename
			
		if not filename:
			filename = QtGui.QFileDialog.getSaveFileName(
				self,
				self.tr("Save File"),
				"",
				self.tr("All Files(*)")
			)
	
		if filename:
			title = filename.split("/")[-1]
			
			outputFile = open(filename,'w')
			outputFile.write( editor.getPlainText() )
			outputFile.close()
			
			editor.setFilename( filename )
			self.parentWindow.updateTitle( title )
			self.setTabText(self.currentTab, title )
